/**
 * 
 */
package com.kgcx.schedule.rabbitmq.consumer;

import com.kgcx.common.constant.Cons;
import com.kgcx.common.rabbitmq.consts.QueueConst;
import com.kgcx.core.utils.HelpUtil;
import com.kgcx.dbutils.core.model.ParameterMap;
import com.kgcx.schedule.domain.ScheduleRecordDomain;
import com.kgcx.schedule.service.ScheduleOrderService;
import com.kgcx.schedule.service.ScheduleRecordService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.List;

/**
 * @author 袁进勇
 *
 */
@Component

public class ScheduleDrvierConsumer extends AbstractScheduleConsumer {
    private static final Logger LOG = LoggerFactory.getLogger(ScheduleDrvierConsumer.class);

    @Resource
    private ScheduleRecordService scheduleRecordService;

    @RabbitListener(queues = QueueConst.SCHEDULE_SCHEDULE_DRVIER_CITY, errorHandler = "custRabbitListenerErrorHandler")
    public void scheduling(Long cityId) {
        LOG.info(String.format("收到给城市[%d]的订单派车的MQ消息。", cityId));

        ParameterMap params = new ParameterMap("city_id", cityId);
        params.put("schedule_task", Cons.BOOLEAN_TRUE);
        params.put("schedule_status", ScheduleRecordDomain.STATUS_PENDING);
        params.put("latest_schedule_time_end", HelpUtil.getNowTime());
        params.setOrderBy("plan_depart_time, create_time");
        List<ScheduleRecordDomain> records = scheduleRecordService.selectEntityListPage(params);
        if (HelpUtil.isEmpty(records)) {
            LOG.info(String.format("城市[%d]待派车的订单数为0。", cityId));
            return;
        }

        for (ScheduleRecordDomain record : records) {
            ScheduleOrderService scheduleOrderService = getScheduleOrderService(record.getOrder_type());
            if (scheduleOrderService == null) {
                LOG.error(String.format("订单[%s]处理失败，未知的订单类型[%d]！", record.getOrder_no(), record.getOrder_type()));
                continue;
            }

            scheduleOrderService.scheduleRecord(record);
        }
    }
}
